package com.im.server;

import com.im.common.config.ImServerConfig;
import com.im.server.init.ImServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

/**
 * @author gongym
 * @date 2019/1/9 13:05
 */
@Component
public class ImServer {
  private static final Logger LOGGER = LoggerFactory.getLogger(ImServer.class);
  private EventLoopGroup boss = new NioEventLoopGroup();
  private EventLoopGroup work = new NioEventLoopGroup();
  private ImServerConfig imServerConfig;

  @Autowired
  public ImServer(ImServerConfig imServerConfig) {
    this.imServerConfig = imServerConfig;
  }

  @PostConstruct
  public void start() throws InterruptedException {
    ServerBootstrap bootstrap =
        new ServerBootstrap()
            .group(boss, work)
            .channel(NioServerSocketChannel.class)
            .localAddress(new InetSocketAddress(imServerConfig.getPort()))
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new ImServerInitializer());
    ChannelFuture future = bootstrap.bind().sync();
    if (future.isSuccess()) {
      LOGGER.info("启动 im server 成功");
    }
  }
  /** 销毁 */
  @PreDestroy
  public void destroy() {
    boss.shutdownGracefully().syncUninterruptibly();
    work.shutdownGracefully().syncUninterruptibly();
    LOGGER.info("关闭 im server 成功");
  }
}
